package com.example.service.Impl;

import cn.hutool.core.util.StrUtil;
import com.example.common.Result;
import com.example.exception.CustomException;
import com.example.mapper.UserMapper;
import com.example.pojo.Account;
import com.example.pojo.Admin;
import com.example.pojo.LoginResponse;
import com.example.pojo.User;
import com.example.service.UserService;
import com.example.util.JwtUtil;
import com.example.util.Md5Util;
import com.example.util.ThreadLocalUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestHeader;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 添加用户
     *
     * @param user
     */
    @Override
    public void add(User user) {
        User dbUser = userMapper.selectByUsername(user.getUsername());
        if (dbUser !=null){
            throw new CustomException("500","账号已存在");
        }
        if (StrUtil.isBlank(user.getPassword())){//未填密码
            user.setPassword("12345");//设置默认密码
        }

        if (StrUtil.isBlank(user.getName())){//未填姓名
            user.setName(user.getUsername());//设置账号为默认姓名
        }

        if (StrUtil.isBlank(user.getAvatar())){
            user.setAvatar("https://house1205.oss-cn-shenzhen.aliyuncs.com/%E9%BB%98%E8%AE%A4%E5%A4%B4%E5%83%8F.png");
        }
        user.setRole("user");//设置角色为普通用户

        String md5String = Md5Util.getMD5String(user.getPassword());//加密密码
        user.setPassword(md5String);

        userMapper.add(user);
    }

    /**
     * 注册
     *
     * @param user
     */
    @Override
    public void register(User user) {
        this.add(user);
    }

    /**
     * 修改密码
     *
     * @param account
     */
    @Override
    public void updatePassword(Account account, @RequestHeader("Authorization") String token) {
        Integer id = account.getId();
        User dbUser = userMapper.selectById(id);
        if (!dbUser.getPassword().equals(Md5Util.getMD5String(account.getPassword()))){
            throw new CustomException("500","原密码错误");
        }
        dbUser.setPassword(Md5Util.getMD5String(account.getNewPassword()));

        this.updateById(dbUser);

        //修改密码后，注销token
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.getOperations().delete(token);
    }

    /**
     * 登录
     *
     * @param account
     */
    @Override
    public LoginResponse login(Account account) {
        String username = account.getUsername();//账号
        User dbUser = userMapper.selectByUsername(username);
        if (dbUser == null){
            throw new CustomException("500","账号不存在");
        }
        String password = account.getPassword();//密码
        if (!Md5Util.checkPassword(password,dbUser.getPassword())){
            throw new CustomException("500","用户名或密码错误");
        }

        //登录成功
        Map<String, Object> claims = new HashMap<>();
        claims.put("id",dbUser.getId());
        claims.put("username",username);
        claims.put("name",dbUser.getName());
        claims.put("role",dbUser.getRole());
        //登录成功后，返回token
        String token = JwtUtil.genToken(claims);

        //把token存储到redis中
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.set(token,token,2, TimeUnit.HOURS);//过期时间 2小时

        LoginResponse loginResponse = new LoginResponse();
        loginResponse.setAccount(dbUser);
        loginResponse.setToken(token);
        return loginResponse;
    }



    /**
     * 查询所有用户
     *
     * @return
     */
    @Override
    public List<User> selectAll(User user) {

        List<User> list = userMapper.selectAll(user);
        return list;
    }

    @Override
    public User selectByUsername(String username) {
        User user = userMapper.selectByUsername(username);
        return user;
    }

    /**
     * 根据id查询用户
     *
     * @param id
     * @return
     */
    @Override
    public User selectById(Integer id) {

        User user = userMapper.selectById(id);
        return user;
    }

    /**
     * 删除
     *
     * @param id
     */
    @Override
    public void deleteById(Integer id) {
        userMapper.deleteById(id);
    }

    /**
     * 批量删除数据
     *
     * @param ids
     */
    @Override
    public void deleteBatch(List<Integer> ids) {
        for (Integer id:ids)
            userMapper.deleteById(id);
    }



    /**
     * 修改用户
     *
     * @param user
     */
    @Override
    public void updateById(User user) {
        userMapper.updateById(user);
    }



    /**
     * 分页查询
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<User> selectPage(User user, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<User> list = userMapper.selectAll(user);
        return PageInfo.of(list);
    }
}
